<script setup lang="ts">
import { GlobalInfo } from "../GlobalInfo"
import { AdminService } from "../apis/AdminService"
import { DocService } from "../apis/DocService"
import { ref, reactive, onMounted, computed } from "vue"
import { useToast } from "vue-toastification";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();
const toast = useToast();

const isEditing = GlobalInfo.isEditing;
const newCategoryCaption = ref("");
const isLoading = ref(true);
const subMenus = GlobalInfo.SubMenus;

const categories: any[] = reactive([]);
const currentId = GlobalInfo.CurrentDocId;
const justClicked = ref(false);

const newCategoryOK = async (event: KeyboardEvent) => {
    if (event.keyCode == 13) {
        try {
            //新增分类
            var dataitem: any = await AdminService.AddCategory(newCategoryCaption.value);
            console.log("new item:", dataitem);
            categories.push(dataitem);
            newCategoryCaption.value = "";
        }
        catch (e) {
            GlobalInfo.showError(e);
        }
    }
}

const newDocOK = async (event: KeyboardEvent, category: any) => {
    if (event.keyCode == 13) {
        try {
            //新增doc
            var caption = (<any>event.target).value;
            var dataitem = await AdminService.AddDoc(caption, category.Id);
            category.Documents.push(dataitem);
            (<any>event.target).value = "";
        }
        catch (e) {
            GlobalInfo.showError(e);
        }
    }
}

const updateDocOK = async (event: KeyboardEvent, category: any, doc: any) => {
    if (event.keyCode == 13) {
        try {
            //编辑doc
            if (doc.Caption == "") {
                //删除
                await AdminService.DeleteDoc(doc.Id);
                category.Documents.splice(category.Documents.indexOf(doc), 1);
            }
            else {
                await AdminService.UpdateDoc(doc.Caption, undefined, doc.Id);
                toast("名称修改成功");
            }
        }
        catch (e) {
            GlobalInfo.showError(e);
        }
    }
}

const updateCategoryOK = async (event: KeyboardEvent, category: any) => {
    if (event.keyCode == 13) {
        try {
            //编辑分类
            if (category.Caption == "") {
                //删除
                await AdminService.DeleteCategory(category.Id);
                categories.splice(categories.indexOf(category), 1);
            }
            else {
                await AdminService.UpdateCategory(category.Id, category.Caption);
                toast("名称修改成功");
            }
        }
        catch (e) {
            GlobalInfo.showError(e);
        }
    }
}

onMounted(async () => {
    GlobalInfo.ScrollToActiveItemFun = scrollToActiveItem;
    try {
        var items = await DocService.GetDocuments();

        categories.push(...items);

        if (location.search && location.search.length > 1) {

            var path = location.search.substring(1);
            // 删除查询字符串
            var newUrl = location.href.replace(location.search, '');

            // 使用replaceState方法更新URL但不触发跳转
            window.history.replaceState({}, document.title, newUrl);

            router.push(`/${path}`);
        }
        else if (location.href.indexOf("/#/") < 0 || location.href.endsWith("/#/")) {
            if (!GlobalInfo.CurrentDocId.value && items.length > 0 && items[0].Documents.length) {
                router.push(`/doc/${items[0].Documents[0].Id}/${items[0].Documents[0].Version}/0`)
            }
        }
    }
    catch (e) {
        GlobalInfo.showError(e);
    }
    finally {
        isLoading.value = false;
    }
})

const iconClick = (event: MouseEvent) => {
    if (event.ctrlKey && event.altKey) {
        router.push("/login");
    }
}

var lastTitleClickSource: HTMLElement;
const titleObjClick = (event: MouseEvent, titleObj: any) => {

    if (lastTitleClickSource) {
        lastTitleClickSource.setAttribute("actived", "0");
    }
    lastTitleClickSource = <HTMLElement>event.target;
    lastTitleClickSource.setAttribute("actived", "1");
    const heading: HTMLElement = <HTMLElement>GlobalInfo.Preview.$el.querySelector(`[data-v-md-line="${titleObj.lineIndex}"]`);


    if (heading) {
        var parent: HTMLElement = <HTMLElement>heading.parentElement;
        while (parent && parent.className.indexOf("container") < 0) {
            parent = <HTMLElement>parent.parentElement;
        }

        GlobalInfo.Preview.scrollToTarget({
            target: heading,
            scrollContainer: parent,
            top: 60,
        });
    }
}

const upCategoryClick = async (category: any): Promise<void> => {
    var index = categories.indexOf(category);
    if (index > 0) {
        categories.splice(index, 1);
        categories.splice(index - 1, 0, category);
        await AdminService.UpdateCategorySorts(categories.map(m => m.Id));
    }
}
const downCategoryClick = async (category: any): Promise<void> => {
    var index = categories.indexOf(category);
    if (index < categories.length - 1) {
        categories.splice(index, 1);
        categories.splice(index + 1, 0, category);
        await AdminService.UpdateCategorySorts(categories.map(m => m.Id));
    }
}
const upDocClick = async (category: any, doc: any): Promise<void> => {
    var index = category.Documents.indexOf(doc);
    if (index > 0) {
        category.Documents.splice(index, 1);
        category.Documents.splice(index - 1, 0, doc);
        await AdminService.UpdateDocSorts(category.Documents.map((m: any) => m.Id));
    }
}
const downDocClick = async (category: any, doc: any): Promise<void> => {
    var index = category.Documents.indexOf(doc);
    if (index < category.Documents.length - 1) {
        category.Documents.splice(index, 1);
        category.Documents.splice(index + 1, 0, doc);
        await AdminService.UpdateDocSorts(category.Documents.map((m: any) => m.Id));
    }
}

const scrollToActiveItem = () => {
    if (justClicked.value) {
        justClicked.value = false;
        return;
    }

    if (!GlobalInfo.CurrentDocId.value)
        return;

    var ele = document.body.querySelector("#doc" + GlobalInfo.CurrentDocId.value);
    if (!ele) {
        window.setTimeout(scrollToActiveItem, 100);
        return;
    }

    if (ele.getBoundingClientRect().top > document.body.offsetHeight / 2) {
        ele.scrollIntoView();
    }

}
</script>

<template>
    <div id="root">
        <div class="icon" @click="iconClick"></div>

        <div class="menucontainer">
            <div class="menu" v-if="isLoading" style="font-weight:normal;">正在加载...</div>
            <div class="menu" v-for="category in categories">
                <span v-if="!isEditing">{{ category.Caption }}</span>

                <button v-if="isEditing" @click="upCategoryClick(category)">上</button>
                <button v-if="isEditing" @click="downCategoryClick(category)">下</button>
                <input v-if="isEditing" style="font-weight: 600;" v-model="category.Caption"
                    @keypress="updateCategoryOK($event, category)">

                <div :id="'doc' + doc.Id" class="submenu" :class="{ editing: isEditing }" v-for="doc in category.Documents">
                    <RouterLink @click="justClicked = true" :actived="currentId == doc.Id ? '1' : '0'" v-if="!isEditing"
                        :to="`/doc/${doc.Id}/${doc.Version}`">{{ doc.Caption }}
                    </RouterLink>

                    <button v-if="isEditing" @click="upDocClick(category, doc)">上</button>
                    <button v-if="isEditing" @click="downDocClick(category, doc)">下</button>
                    <input v-if="isEditing" v-model="doc.Caption" @keypress="updateDocOK($event, category, doc)">
                    <RouterLink v-if="isEditing" :to="`/editor/${doc.Id}`">Open</RouterLink>
                    <div v-if="!isEditing && currentId == doc.Id && subMenus.length > 1">
                        <div class="submenu2" v-for="subtitle in subMenus" @click="titleObjClick($event, subtitle)">
                            {{ subtitle.title }}</div>
                    </div>

                </div>
                <div class="submenu editing" v-if="isEditing"><input @keypress="newDocOK($event, category)"></div>
            </div>

            <div class="menu" v-if="isEditing"><input v-model="newCategoryCaption" @keypress="newCategoryOK"></div>
        </div>
    </div>
</template>

<style scoped>
#root {
    user-select: none;
    min-width: 230px;
    height: 100vh;

    overflow-x: hidden;
    overflow-y: auto;
    border-right: 1px solid #eee;


}

.editing {
    margin-left: 30px;
}

.menucontainer {
    padding-left: 30px;
    padding-bottom: 30px;
}

.icon {
    width: 100%;
    height: 121px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;

    background-image: url(@/assets/JMS.svg);
    background-size: 360px;
    background-position-x: center;
    background-position-y: -75px;
    background-repeat: no-repeat;
}

.icon img {
    width: 600px;
    height: 442px;
    scale: 0.6;
}

.menu {
    display: block;
    line-height: 25px;
    font-size: 14px;
    font-weight: 600;
    color: #213547;
    margin-top: 5px;
}

.submenu {
    line-height: 25px;
    font-weight: normal;
    display: block;
    color: rgba(60, 60, 60, .7);
    cursor: pointer;
}

.submenu2 {
    padding-left: 15px;
}

div[actived="1"] {
    color: #42b883;
}

a[actived="1"] {
    color: #42b883;

    font-weight: 600;
}

a {
    text-decoration: none;
    color: rgba(60, 60, 60, .7);
    font-weight: normal;
}
</style>